# -- coding: utf-8 --
"""
# [Example] Miahx© 交互框架信息表示模型的 DDS 消息收发示例

**模块：MIAHX© / 框架基础服务层（FFST） / 交互框架信息表示模型（IFIRM）**

Version: 0.4.10,
Last updated: October 6, 2024

## Contributor(s)
* YAO Naiming <[naiming@iscas.ac.cn](mailto:naiming@iscas.ac.cn)>

## Change log
### v0.4.10
- .6: [更新] 适配新接口，新增 periods 字段
### v0.4.7
- .24: [新增] 初始实现

---
Copyright © 2024-2025 MIAHX Contributors, ISCAS, and ASIC. All Rights Reserved.
Licensed under Apache-2.0.
"""

import datetime
import threading
import time

from miahx_support.dds.fastdds import *

import launcher


def gnss_writer(p: Participant, e: threading.Event):
    writer = GNSSWriter(p)
    isn, periods = 0, 1.0
    while not e.is_set():
        isn = (isn + 1) % (10 ** 5)
        now = datetime.datetime.now()
        writer.write(year=now.year, month=now.month, day=now.day,
                     hour=now.hour, minute=now.minute, second=now.second,
                     ns=now.microsecond * 1000, isn=isn, periods=periods)
        time.sleep(periods)


def gnss_reader(p: Participant, e: threading.Event):
    def on_gnss_available(data):
        d = data.header().domain()
        s = data.header().source()
        dt = datetime.datetime(data.year(), data.month(), data.day(),
                               data.hour(), data.min(), data.sec(),
                               int(data.ns() / 1000.0))
        log.info(f'[{d}::{s}::GNSSReader] [{data.iid():>08d}] datetime = `{dt}`, periods = `{data.periods():.3f}`')

    with GNSSReader(p, on_data_listeners=[on_gnss_available]) as reader:
        log.success(f'[GNSSReader] Reading topic `{reader.topic_name}` ...')
        reader.wait(e)


if __name__ == '__main__':
    log = launcher.log
    event = threading.Event()
    participant = Participant()
    launcher.run(lambda: (event, [
        threading.Thread(target=gnss_writer, args=(participant, event), daemon=False),
        threading.Thread(target=gnss_reader, args=(participant, event), daemon=False),
    ]))
